package cn.bitkit.tools.data;

import cn.bitkit.base.util.StringUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Function;

public class TreeUtil {

    public static <T, K> List<T> asTree(List<T> list, K parentId, Function<T, K> getId, Function<T, K> getParentId, BiConsumer<T, List<T>> setSubList){
        List<T> tree = new ArrayList<>();
        list.forEach( t -> {
            if(parentId == null && getParentId.apply(t) == null
                || parentId != null && StringUtil.isEqual(StringUtil.getValue(parentId), StringUtil.getValue(getParentId.apply(t)))){
                List<T> subtree = asTree(list, getId.apply(t), getId, getParentId, setSubList);
                setSubList.accept(t, subtree);
                tree.add(t);
            }
        });
        return tree;
    }

}
